package com.group6.exam.teacher.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.group6.exam.teacher.entity.ScoreCondition;
import com.group6.exam.teacher.entity.ScorePage;
import com.group6.exam.teacher.service.IScoreService;
import com.group6.exam.teacher.service.ScoreServiceImpl;

public class ScoreServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String command = request.getParameter("command");

		if ("query".equals(command)) {
			query(request, response);
		} else {
			throw new RuntimeException("請求失敗" + command);
		}
	}

	/**
	 * 查询
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void query(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		IScoreService service = new ScoreServiceImpl();

		ScoreCondition condition = new ScoreCondition();
		String subjectName = request.getParameter("subjectName");
		String className = request.getParameter("className");
		String studentName = request.getParameter("studentName");

		if (subjectName != null && !"".equals(subjectName)) {
			String subStr = "%" + subjectName + "%";
			String sujectId = service.getScoreBySubName(subStr);
			condition.setSubjectId(sujectId);
		}
		if (className != null && !"".equals(className)) {
			String claStr = "%" + className + "%";
			String classId = service.getScoreByClaName(claStr);
			condition.setClassId(classId);
		}
		if (studentName != null && !"".equals(studentName)) {
			String stuStr = "%" + studentName + "%";
			String studentId = service.getScoreByStuName(stuStr);
			condition.setClassId(studentId);
		}

		// 创建调用分页业务方法所需参数
		ScorePage scorePage = new ScorePage();
		String pageNo = request.getParameter("currentPage");
		// 获取当前页数
		int currentPage = !"".equals(pageNo) && pageNo != null ? Integer
				.valueOf(pageNo) : 1;
		scorePage.setCurrentPage(currentPage);
		// 调用分页的业务方法
		ScorePage paging = service
				.getScoreInfoByScorePage(scorePage, condition);

		request.setAttribute("scorePage", paging);
		request.getRequestDispatcher(
				"view/teacher/score-admin/score-maintain.jsp").forward(request,
				response);
	}
}
